<template>
  <div class="btn_warp" style="height:32px;width: 100%;padding-top: 5px;padding-bottom: 10px">
    <el-button type="success" plain class="btn_add" style="width:100px" @click="onAddItem">添加</el-button>
    <el-button type="danger" plain class="btn_delete" style="width: 100px" @click="onDeleteItem">删除</el-button>
    <el-button type="success" style="float: right;margin-right: 30px" @click.prevent="handleSearch">查询</el-button>
    <el-button type="success" style="float: right;margin-right: 5px" @click.prevent="handleClean">全部清空</el-button>
    <el-input v-model="search3" clearable placeholder="按户型查询" style="float: right;width: 250px;margin-right: 15px"/>
    <el-input v-model="search2" clearable placeholder="按是否出售查询" style="float: right;width: 250px;margin-right: 15px"/>
    <el-input v-model="search1" clearable placeholder="按物业地址查询" style="float: right;width: 250px;margin-right: 15px"/>
  </div>
  <el-table @selection-change="handleSelsChange" :data="filterTableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" stripe border style="width: 1145px;margin: 0 auto" max-height="472" height="472" :cell-style="{ textAlign: 'center' }">
    <el-table-column type="selection" width="40" >
    </el-table-column>
    <el-table-column fixed prop="" label="序号" width="70" :show-overflow-tooltip="true">
      <template #default="scope">
        {{scope.$index+1}}
      </template>
    </el-table-column>
    <el-table-column fixed prop="propertyAddress" label="物业地址" width="120" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.propertyAddress" maxlength="30" size="large"/>
            </span>
        <span v-else>{{ scope.row.propertyAddress }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="propertyIssell" label="是否出售" width="90" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate && !scope.row.isAdd">
              <el-select v-model="scope.row.propertyIssell" placeholder="选择" size="small">
                <el-option v-for="item in isSellOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </span>
        <span v-else>{{ scope.row.propertyIssell }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="householdName" label="业主姓名" width="100" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate && !scope.row.isAdd">
              <el-input input-style="height:23px" class="table-input" v-model="scope.row.householdName" maxlength="30" size="large"/>
            </span>
        <span v-else>{{ scope.row.householdName }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="propertyType" label="户型" width="100" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-select v-model="scope.row.propertyType" placeholder="选择" size="small">
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </span>
        <span v-else>{{ scope.row.propertyType }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="propertyDecorate" label="装修情况" width="100" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-select v-model="scope.row.propertyDecorate" placeholder="选择" size="small">
                <el-option v-for="item in decorateOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </span>
        <span v-else>{{ scope.row.propertyDecorate }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="propertyAllarea" label="建筑面积(m²)" width="130" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input-number input-style="height:23px;" :min="0" :max="1000" size="small" controls-position="right" class="table-input" v-model="scope.row.propertyAllarea" />
            </span>
        <span v-else>{{scope.row.propertyAllarea}}</span>
      </template>
    </el-table-column>
    <el-table-column prop="propertyUsearea" label="使用面积(m²)" width="130" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input-number input-style="height:23px;" :min="0" :max="1000" size="small" controls-position="right" class="table-input" v-model="scope.row.propertyUsearea" />
            </span>
        <span v-else>{{ scope.row.propertyUsearea }}</span>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="265" :show-overflow-tooltip="true">
      <template #default="scope">
        <el-button type="warning" round size="small" @click.prevent="updateRow(scope.$index)">修改</el-button>
        <el-button type="primary" round size="small" @click.prevent="saveRow(scope.$index,scope.row.propertyId)">保存</el-button>
        <el-button type="danger" round size="small" @click.prevent="deleteRow(scope.row.propertyId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="page_warp">
    <el-pagination  background @current-change="handleCurrentChange" v-model:page-size="pageSize" v-model:current-page="currentPage" layout="prev, pager, next , jumper" :total="filterTableData.length"></el-pagination>
  </div>
</template>

<script>
import { ElMessage,ElMessageBox } from 'element-plus'
import {ref,onMounted} from 'vue'
import {nanoid} from 'nanoid'
import axios from "axios"
import {useRouter} from 'vue-router'

export default {
  name: "HouseHold",
  setup(){
    const tableSels=ref([])
    const tableData = ref([ ])
    const pageSize=ref(10)
    const currentPage=ref(1)
    const router=useRouter()
    const isSellOptions=[
      {
        value:'是',
        label:'是'
      },
      {
        value:'否',
        label:'否'
      }
    ]
    const typeOptions=[
      {
        value:'一居室',
        label:'一居室'
      },
      {
        value:'二居室',
        label:'二居室'
      },
      {
        value:'三居室',
        label:'三居室'
      },
      {
        value:'多居室',
        label:'多居室'
      }
    ]
    const decorateOptions=[
      {
        value:'已装修',
        label:'已装修'
      },
      {
        value:'装修中',
        label:'装修中'
      },
      {
        value:'未装修',
        label:'未装修'
      }
    ]
    const search1=ref('')
    const search2=ref('')
    const search3=ref('')
    //条件过滤
    let filterTableData =ref([])

    //按条件进行查询
    function handleSearch(){
      filterTableData.value=tableData.value.filter(
          (data) => data.propertyAddress.toLowerCase().includes(search1.value.toLowerCase()) //匹配物业地址
              && data.propertyIssell.toLowerCase().includes(search2.value.toLowerCase()) //匹配是否出售
              && data.propertyType.toLowerCase().includes(search3.value.toLowerCase()) //匹配户型
      )
    }
    //清空查询条件
    function handleClean(){
      search1.value=''
      search2.value=''
      search3.value=''
    }
    //选择添加事件
    function onAddItem(){
      tableData.value.push({
            propertyId:nanoid(),   //房产id
            propertyForeignkey:'',   //住户id
            propertyAddress: '',  //物业地址
            propertyIssell: '否',  //是否出售
            householdName: '',  //业主姓名
            propertyType: '二居室',  //户型
            propertyDecorate: '未装修',  //装修情况
            propertyAllarea: 0,  //建筑面积
            propertyUsearea: 0,  //使用面积
            isUpdate:true,    //是否为编辑状态
            isAdd:true,    //是否为新增状态
      })
      console.log(tableData)
      currentPage.value=Math.ceil(tableData.value.length/pageSize.value)
    }
    //选择删除事件
    function onDeleteItem(){
      ElMessageBox.confirm('确认删除此记录吗？', '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning',}).then(() => {
        tableSels.value.forEach((tableSel)=>{
          tableData.value.forEach((item,index)=>{
            if(item.propertyId===tableSel.propertyId){
              tableData.value.splice(index,1)
              axios.get('http://localhost:8085/deleteProperty',{
                params:{
                  propertyId:item.propertyId,   //房产id
                }
              }).then(
                  ()=>{
                    ElMessage({type:'success',message:'删除成功！'})
                  },
                  ()=>{
                    ElMessage({type:'error',message:'删除失败！'})
                    setTimeout(()=>{
                      router.go(0)
                    },500)
                  }
              )
            }
          })
        })
      }).catch(() => {
        ElMessage({type: 'error', message: '删除失败！',})
      })
    }
    //行修改事件
    function updateRow(index) {
      filterTableData.value[pageSize.value * (currentPage.value - 1) + index].isUpdate = true
    }
    //行保存事件
    function saveRow(index){
      let propertyObj=filterTableData.value[pageSize.value*(currentPage.value-1)+index]
      if(!propertyObj.isUpdate){
        ElMessage({message:'没有数据需要保存！'})
      }else if(propertyObj.propertyAddress === ''){
        ElMessage({message:'物业地址不能为空！'})
      }else if(propertyObj.propertyIssell === ''){
        ElMessage({message:'是否出售不能为空！'})
      }else if(propertyObj.propertyIssell === '否' && propertyObj.householdName !=''){
        ElMessage({message:'该房产暂未出售，业主姓名无效！'})
      } else if(propertyObj.propertyIssell === '是' && propertyObj.householdName==='') {
        ElMessage({message:'请输入业主姓名！'})
      }else if(propertyObj.isAdd){
        if(isRepeat(propertyObj,index)) return
        axios.get('http://localhost:8085/addProperty',{
          params:{
            propertyId:propertyObj.propertyId,   //房产id
            propertyForeignkey:propertyObj.propertyForeignkey,   //住户id
            propertyAddress: propertyObj.propertyAddress,  //物业地址
            propertyIssell: propertyObj.propertyIssell,  //是否出售
            householdName: propertyObj.householdName,  //业主姓名
            propertyType: propertyObj.propertyType,  //户型
            propertyDecorate: propertyObj.propertyDecorate,  //装修情况
            propertyAllarea: propertyObj.propertyAllarea,  //建筑面积
            propertyUsearea: propertyObj.propertyUsearea,  //使用面积
          }
        }).then(
            ()=>{
              ElMessage({type:'success',message:'保存成功！'})
              propertyObj.isUpdate=false
              propertyObj.isAdd=false
            },
            ()=>{
              ElMessage({type:'error',message:'保存失败！'})
            }
        )
      }else if(propertyObj.propertyIssell === '是' && propertyObj.householdName !=''){
        if(isRepeat(propertyObj,index)) return
        //1.发送请求判断业主是否存在
        axios.get('http://localhost:8085/hasHousehold',{
          params:{
            householdName:propertyObj.householdName,   //业主姓名
            propertyAddress:propertyObj.propertyAddress //物业地址
          }
        }).then(
            (resp)=>{
              if(resp.data){
                //存在则请求进行数据保存获取住户编号
                axios.get('http://localhost:8085/updateProperty',{
                  params:{
                    propertyId:propertyObj.propertyId,   //房产id
                    propertyForeignkey:propertyObj.propertyForeignkey,   //住户id
                    propertyAddress: propertyObj.propertyAddress,  //物业地址
                    propertyIssell: propertyObj.propertyIssell,  //是否出售
                    householdName: propertyObj.householdName,  //业主姓名
                    propertyType: propertyObj.propertyType,  //户型
                    propertyDecorate: propertyObj.propertyDecorate,  //装修情况
                    propertyAllarea: propertyObj.propertyAllarea,  //建筑面积
                    propertyUsearea: propertyObj.propertyUsearea,  //使用面积
                  }
                }).then(
                    ()=>{
                      ElMessage({type:'success',message:'保存成功！'})
                      propertyObj.isUpdate=false
                    },
                    ()=>{
                      ElMessage({type:'error',message:'保存失败！'})
                    }
                )
              }else{
                //2.不存在则进行提示
                ElMessage({type:'error',message:'保存失败，业主不存在！'})
              }
            },
            ()=>{
              ElMessage({type:'error',message:'保存失败！'})
            }
        )
      }else{
        if(isRepeat(propertyObj,index)) return
        axios.get('http://localhost:8085/updateProperty',{
          params:{
            propertyId:propertyObj.propertyId,   //房产id
            propertyForeignkey:propertyObj.propertyForeignkey,   //住户id
            propertyAddress: propertyObj.propertyAddress,  //物业地址
            propertyIssell: propertyObj.propertyIssell,  //是否出售
            householdName: propertyObj.householdName,  //业主姓名
            propertyType: propertyObj.propertyType,  //户型
            propertyDecorate: propertyObj.propertyDecorate,  //装修情况
            propertyAllarea: propertyObj.propertyAllarea,  //建筑面积
            propertyUsearea: propertyObj.propertyUsearea,  //使用面积
          }
        }).then(
            ()=>{
              ElMessage({type:'success',message:'保存成功！'})
              propertyObj.isUpdate=false
            },
            ()=>{
              ElMessage({type:'error',message:'保存失败！'})
            }
        )
      }
    }
    //行删除事件
    function deleteRow(propertyId){
      ElMessageBox.confirm('确认删除此记录吗？', '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning',}).then(() => {
        tableData.value.forEach((item,index)=>{
          if(item.propertyId===propertyId){
            tableData.value.splice(index,1)
            axios.get('http://localhost:8085/deleteProperty',{
              params:{
                propertyId:propertyId,   //房产id
              }
            }).then(
                ()=>{
                  ElMessage({type:'success',message:'删除成功！'})
                },
                ()=>{
                  ElMessage({type:'error',message:'删除失败！'})
                }
            )
          }
        })
        // filterTableData.value.splice(index,1)
      }).catch(() => {
        ElMessage({type: 'info', message: '删除失败！',})
      })
    }
    //分页事件
    function handleCurrentChange(value){
      currentPage.value = value;
    }
    //处理多选
    const handleSelsChange=(sels)=>{
      tableSels.value=sels
    }
    //挂载加载数据
    onMounted(()=>{
      console.log("挂载请求数据")
      axios.get('http://localhost:8085/getProperty').then(
          (response)=>{
            tableData.value=response.data
            filterTableData.value=response.data
          },
          (erro)=>{
            console.log(erro.message)
          }
      )
    })
    //Date格式化
    function formatDate(date, fmt) {
      if (typeof date == 'string') {
        return date
      }

      if (!fmt) fmt = 'yyyy-MM-dd'

      if (!date || date == null) return null
      const o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
      }
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
            RegExp.$1,
            `${date.getFullYear()}`.substr(4 - RegExp.$1.length)
        )
      for (const k in o) {
        if (new RegExp(`(${k})`).test(fmt))
          fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
          )
      }
      return fmt
    }
    //判断记录是否重复
    function isRepeat(Obj,index){
      let tip=0
      tableData.value.forEach((item,indexx)=>{
        if(Obj.propertyAddress==item.propertyAddress && (pageSize.value*(currentPage.value-1)+index)!=indexx){
          tip=1
        }
      })
      if(tip==1){
        ElMessage({type:'error',message:'保存失败,该房产信息记录已存在！'})
        return true
      }else{
        return false
      }
    }

    return{
      tableSels,
      tableData,
      filterTableData,
      search1,
      search2,
      search3,
      pageSize,
      currentPage,
      formatDate,
      onAddItem,
      onDeleteItem,
      updateRow,
      saveRow,
      deleteRow,
      handleCurrentChange,
      handleSelsChange,
      isSellOptions,
      typeOptions,
      decorateOptions,
      isRepeat,
      handleSearch,
      handleClean
    }
  }
}
</script>

<style scoped>
  .el-table{
    /*padding: 20px 20px 20px 20px;*/
  }
  .page_warp{
    width: 600px;
    margin: 5px auto;
    height: 40px;
  }
  .el-pagination{
    margin-right: 50px;
  }
  .demo-date-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
  }
  .el-input-number--small{
    width: 100px;
  }
</style>